// pages/communityList/communityList.js
const {
  getCommunity,
  searchCommunity
} = require('../../services/communityListReq')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    searchPageNum: 1,
    pageSize: 10,
    communityList: [],
    searchValue: '',
    searchList: [],
    isFinish: false,
    isSearchFinish: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.handleGetCommunity()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.searchValue === '') {
      this.setData({
        pageNum: this.data.pageNum + 1
      })
      this.handleGetCommunity()
    } else {
      this.setData({
        searchPageNum: this.data.searchPageNum + 1
      })
      this.handleSearchCommunity()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 获取社团列表
  handleGetCommunity() {
    if (this.data.isFinish) {
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    getCommunity(this.data.pageNum, this.data.pageSize, res => {
      console.log(res.data.data)
      let list = res.data.data.list
      list.forEach(val =>{
        try{
          val.communityAddress = JSON.parse(val.communityAddress).address
        }catch (e) {
          console.log(e)
        }
      })
      if (list.length < this.data.pageSize) {
        this.setData({
          isFinish: true
        })
      }
      this.setData({
        communityList: this.data.communityList.concat(list)
      })
      wx.hideLoading()
    })
  },

  // 搜索更新
  handleSearchChange(e) {
    this.setData({
      searchValue: e.detail,
      searchList: [],
      searchPageNum: 1,
      isSearchFinish: false
    })
  },

  // 搜索社团
  handleSearchCommunity() {
    if (this.data.isSearchFinish) {
      return
    }
    wx.showLoading({
      title: '搜索中',
    })
    searchCommunity(this.data.searchValue, this.data.searchPageNum, this.data.pageSize, res => {
      let list = res.data.data.list
      if (list.length < this.data.pageSize) {
        this.setData({
          isSearchFinish: true
        })
      }
      list.forEach(val =>{
        try{
          val.communityAddress = JSON.parse(val.communityAddress).address
        }catch (e) {
          console.log(e)
        }
      })
      this.setData({
        searchList: this.data.searchList.concat(list)
      })
      wx.hideLoading()
    })
  },

  // 跳转社团详情
  handleGoDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../communityDetail/communityDetail?id=${id}`,
    })
  }
})
